/*
* Copyright (c) 2025 Huawei Device Co., Ltd.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including but not limited to the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to provide persons with access to the Software
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGE OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/

import React, {
  createContext,
  useReducer,
  useContext,
  Dispatch,
  ReactNode,
  ReactElement,
} from 'react';
import touxiang from '../assets/images/touxiang.svg'; // 图片导入
import { MessageItem } from '../types/types';

interface AppState {
  activeItem: MessageItem;
  currentBp: string;
}

// 定义 Action 类型
type AppAction =
  | { type: 'UPDATE_ITEM'; payload: MessageItem }
  | { type: 'UPDATE_CURRENT_BP'; payload: string };

// 初始状态
const initialState: AppState = {
  activeItem: {
    id: '11',
    name: '张晓萌',
    message: '好的，我明天过来',
    time: '13:55',
    avatar: touxiang,
    unread: null,
  },
  currentBp: 'xs',
};

// 创建 Context 类型
interface StoreContextType {
  state: AppState;
  dispatch: Dispatch<AppAction>;
}

const StoreContext = createContext<StoreContextType | undefined>(undefined);

// Reducer 函数
function appReducer(state: AppState, action: AppAction): AppState {
  switch (action.type) {
    case 'UPDATE_ITEM':
      return { ...state, activeItem: action.payload };
    case 'UPDATE_CURRENT_BP':
      return { ...state, currentBp: action.payload };
    default:
      return state;
  }
}

// Provider 组件
export function StoreProvider({ children }: { children: ReactNode }): ReactElement {
  const [state, dispatch] = useReducer(appReducer, initialState);

  return (
    <StoreContext.Provider value={{ state, dispatch }}>
      {children}
    </StoreContext.Provider>
  );
}

// 自定义 Hook - 安全访问 Context
export function useStore(): StoreContextType {
  const context = useContext(StoreContext);
  if (context === undefined) {
    throw new Error('useStore must be used within a StoreProvider');
  }
  return context;
}

// 创建 Action 函数 (可选)
export const updateItem = (item: MessageItem): AppAction => ({
  type: 'UPDATE_ITEM',
  payload: item,
});

export const updateCurrentBp = (bp: string): AppAction => ({
  type: 'UPDATE_CURRENT_BP',
  payload: bp,
});
